package com.tarena.lbs.business.dao.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.business.dao.mapper.StoreMapper;
import com.tarena.lbs.business.dao.repository.StoreRepository;
import com.tarena.lbs.business.pojo.po.StorePO;
import com.tarena.lbs.business.pojo.po.StoreSearchPO;
import com.tarena.lbs.business.pojo.query.AreaStoreQuery;
import com.tarena.lbs.business.pojo.query.StoreQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Repository
public class StoreRepositoryImpl implements StoreRepository {
    @Autowired
    private StoreMapper storeMapper;
    private static final Map<Integer, StorePO> STORE_DB = new HashMap<>();
    private static int ID_GEN = 1;

    @Override
    public List<StorePO> selectStoreById(Integer businessId) {
        LambdaQueryWrapper<StorePO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StorePO::getBusinessId, businessId);
        StoreQuery query = new StoreQuery();
        query.setBusinessId(businessId);
        return storeMapper.selectListByQuery(query);
    }
    @Override
    public PageInfo<StorePO> pageList(StoreQuery query) {
        log.info("模拟分页查询店铺列表，参数={}", query);
        LambdaQueryWrapper<StorePO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StorePO::getBusinessId, query.getBusinessId());
        List<StorePO> list = new ArrayList<>(STORE_DB.values());
        // 使用默认分页参数
        int pageNum = 1;
        int pageSize = 10;
        return mockPage(list, pageNum, pageSize);
    }

    @Override
    public StorePO getById(Integer id) {
        LambdaQueryWrapper<StorePO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StorePO::getId, id);
        log.info("模拟根据ID查询店铺信息，ID={}", id);
        return STORE_DB.get(id);
    }

    @Override
    public Integer add(StorePO storePO) {
        log.info("模拟新增店铺，数据={}", storePO);
        int id = ID_GEN++;
        storePO.setId(id);
        STORE_DB.put(id, storePO);
        return id;
    }

    @Override
    public Integer update(StorePO storePO) {
        log.info("模拟更新店铺，数据={}", storePO);
        if (STORE_DB.containsKey(storePO.getId())) {
            STORE_DB.put(storePO.getId(), storePO);
            return 1;
        }
        return 0;
    }

    @Override
    public PageInfo<StorePO> getStoreByCity(AreaStoreQuery query) {
        log.info("模拟根据城市查询店铺，参数={}", query);
//        LambdaQueryWrapper<StorePO> wrapper = new LambdaQueryWrapper<>();
        List<StorePO> list = new ArrayList<>(STORE_DB.values());

        // 使用反射获取 city 字段
        Object cityObj = getField(query, "city");
        String city = cityObj != null ? cityObj.toString() : "";

        if (city.isEmpty()) {
            return mockPage(list, 1, 10);
        }

        List<StorePO> filtered = list.stream()
                .filter(p -> {
                    Object addressObj = getField(p, "address"); // 替换为你 StorePO 中实际的地址字段名
                    String address = addressObj != null ? addressObj.toString() : "";
                    return address.contains(city);
                })
                .collect(Collectors.toList());

        return mockPage(filtered, 1, 10);
    }

    @Override
    public List<StoreSearchPO> getNearStore(Double lat, Double lon, Double range) {
        log.info("模拟获取附近店铺，坐标=({},{}) 范围={}公里", lat, lon, range);
        // 模拟返回5个店铺
        List<StoreSearchPO> stores = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            StoreSearchPO po = new StoreSearchPO();
            po.setId(i + 1);
//            po.setDistance(10.0 + i); // 距离递增
            stores.add(po);
        }
        return stores;
    }

    // 模拟分页逻辑
    private PageInfo<StorePO> mockPage(List<StorePO> data, int pageNum, int pageSize) {
        int total = data.size();
        int start = Math.min((pageNum - 1) * pageSize, total);
        int end = Math.min(start + pageSize, total);
        List<StorePO> subList = data.subList(start, end);

        PageInfo<StorePO> pageInfo = new PageInfo<>();
        pageInfo.setList(subList);
        pageInfo.setTotal(total);
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        return pageInfo;
    }
    private Object getField(Object obj, String fieldName) {
        try {
            java.lang.reflect.Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            return field.get(obj);
        } catch (Exception e) {
            return null;
        }
    }
}